package com.lenovo.agricultureclient.ui.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.ColoursXYSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import com.lenovo.agricultureclient.AppConfig;
import com.lenovo.agricultureclient.R;
import com.lenovo.agricultureclient.bean.ChartPagerBean;
import com.lenovo.agricultureclient.bean.SensorBean;
import com.lenovo.agricultureclient.bean.SensorConfig;
import com.lenovo.agricultureclient.bean.SensorValue;
import com.lenovo.agricultureclient.db.BaseDB;
import com.lenovo.agricultureclient.db.SensorValueDB;
import com.lenovo.agricultureclient.ui.activity.MainActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
/**
 * 历史数据图表fragment
 * @author zongbingwu
 *
 */
public class HistoryFragment extends AppBaseFragment
{
	public static final String TAG = "HistoryFragment";
	//时间间隔
	private static final long TIMER_PRIOD[] = new long[]{3600000,7200000,14400000,43200000,86400000};
	//传感器类型
	private static final int SENSOR_TYPE_LIST[] = new int[]{R.string.pm25_title,R.string.CO2_title,R.string.light_title,
												R.string.air_tmper_title, R.string.air_humid_title,
												R.string.soil_tmper_title, R.string.soil_humid_title};
	
	private Button mCheckBtn;
	private Spinner mSensorTypeSpinner;
	private Spinner mTimeSpinner;
	
	//默认时间间隔
	private long mTimeGap = 3600000;
	//默认的传感器
	private int mCurrentType = R.string.pm25_title;
	//曲线图表信息对象，最多存储两个曲线图的信息
	private ChartPagerBean mChartPagerBean;
	//传感器值的数据库对象
	private SensorValueDB mSensorValueDB;
	//图表数据集合
	private XYMultipleSeriesDataset mDataset;
	//图表数据渲染器
	private XYMultipleSeriesRenderer mRenderer;
	//图表view
	private GraphicalView mChartView;
	//所有传感器的预警值范围
	private SensorConfig mSensorConfig;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MainActivity mainActivity = (MainActivity)getActivity();
		mSensorValueDB = mainActivity.getSensorValueDB();
		mSensorConfig = mApp.getSensorConfig();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.history_fragment, container, false);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) 
	{
		super.onActivityCreated(savedInstanceState);
		//初始化界面
		initView();
		mChartPagerBean = new ChartPagerBean(getString(R.string.pm25_title));
		mChartPagerBean.majorMax = 500;
		mChartPagerBean.majorMin = 0;
		//刷新曲线图表
		updataChartView();
		//显示加载等待提示框
		showLoadDialog();
		loadSensorDataFromDB();
	}
	
	//初始化界面
	private void initView()
	{
		mCheckBtn = (Button)getView().findViewById(R.id.check_button);
		mCheckBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showLoadDialog();
				loadSensorDataFromDB();
			}
		});
		
		//设置传感器类型下拉列表
		mSensorTypeSpinner = (Spinner)getView().findViewById(R.id.sensor_type_spinner);
		String[] SensorTypeItems = {getString(R.string.pm25_title),getString(R.string.CO2_title),getString(R.string.light_title),
									getString(R.string.air_tmper_title),getString(R.string.air_humid_title),
									getString(R.string.soil_tmper_title), getString(R.string.soil_humid_title)};
		ArrayAdapter<String> tyepAdp = new ArrayAdapter<String>(getActivity(),R.layout.spinner_item,SensorTypeItems);
		tyepAdp.setDropDownViewResource(R.layout.spinner_dropdown);
		mSensorTypeSpinner.setAdapter(tyepAdp);
		mSensorTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
		{
			@Override
		    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,  long arg3) 
			{
				mCurrentType = SENSOR_TYPE_LIST[arg2];
		    }
		    @Override
		    public void onNothingSelected(AdapterView<?> arg0) 
		    {
		    }
		});
		mSensorTypeSpinner.setSelection(0);
		
		//设置时间段下拉列表
		mTimeSpinner = (Spinner)getView().findViewById(R.id.time_spinner);
		String[] timeItems = {getString(R.string.recently_one_hour),getString(R.string.recently_tow_hour),getString(R.string.recently_four_hour),
									getString(R.string.recently_twelve_hour),getString(R.string.recently_one_day),};
		ArrayAdapter<String> timeAdp = new ArrayAdapter<String>(getActivity(),R.layout.spinner_item,timeItems);
		timeAdp.setDropDownViewResource(R.layout.spinner_dropdown);
		mTimeSpinner.setAdapter(timeAdp);
		mTimeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
		{
			@Override
		    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,  long arg3) 
			{
				mTimeGap = TIMER_PRIOD[arg2];
		    }
		    @Override
		    public void onNothingSelected(AdapterView<?> arg0) 
		    {
		    }
		});
		mTimeSpinner.setSelection(0);
	}
	//刷新曲线图表
	private void updataChartView()
	{
		//创建图表数据集合
		mDataset = new XYMultipleSeriesDataset();
		//创建图表数据渲染器
		mRenderer = new XYMultipleSeriesRenderer();
		
		mRenderer.setApplyBackgroundColor(true);//开启背景颜色
	    mRenderer.setAxisTitleTextSize(25);//设置坐标文字尺寸大小
	    mRenderer.setAxesColor(Color.BLACK);///设置坐标文字颜色
	    mRenderer.setChartTitleTextSize(20);//设置图表标题文字尺寸大小
	    mRenderer.setLabelsTextSize(18);//设置刻度显示文字的大小(XY轴都会被设置)
	    mRenderer.setLabelsColor(Color.BLACK);//设置XY轴线的颜色
	    mRenderer.setLegendTextSize(25);//图例文字大小 
	    mRenderer.setMargins(new int[] { 0, 20, 0, 20 });//设置图表的外边框(上/左/下/右)
	    mRenderer.setZoomButtonsVisible(true);//是否显示放大缩小按钮  
	    mRenderer.setPointSize(10);//设置点的大小(图上显示的点的大小和图例中点的大小都会被设置)  
	    
	    mRenderer.setXLabelsColor(Color.WHITE);//设置X轴标签文本的颜色
	    mRenderer.setYLabelsColor(0, Color.WHITE);//设置Y轴标签文本的颜色
	    
	    int yAxisMin = mChartPagerBean.majorMin;//Y轴的最小值
	    int yAxisMax = mChartPagerBean.majorMax;//Y轴的最大值
	    
	    //创建一个数据子集
	    XYSeries seriesMajor = new XYSeries(mChartPagerBean.majorName);
	    int i=1;
	    //将数据添加到数据子集中，并动态修改最大值和最小值
	    for(int value : mChartPagerBean.majorValueList)
	    {
			seriesMajor.add(i, value);
			if(value<yAxisMin){
				yAxisMin = value;
			}
			if(value>yAxisMax){
				yAxisMax = value;
			}
			i++;
	    }
		//将数据子集添加到图表数据集合中
		mDataset.addSeries(seriesMajor);
		//创建一个曲线渲染对象
		ColoursXYSeriesRenderer rendererMajor = new ColoursXYSeriesRenderer();
		rendererMajor.setPointStyle(PointStyle.CIRCLE);//设置为曲线图
		rendererMajor.setFillPoints(true);//数据点被填充
		rendererMajor.setDisplayChartValues(true);//在图表中显示点的值
		rendererMajor.setDisplayChartValuesDistance(1);//在X轴上，设置两点之间的距离
		rendererMajor.setColor(Color.BLUE);//设置点的颜色
		rendererMajor.setChartValuesTextSize(25);//设置点值文本的尺寸大小
		rendererMajor.setChartValuesSpacing(15f);//实时数据文本到中心点的间距
		rendererMajor.setUseColor(true);//设置当前为双色曲线图
		rendererMajor.setPointColor(Color.GREEN);//设置点的颜色
		rendererMajor.setChartValueTextColor(Color.WHITE);//设置数值文本的颜色
		rendererMajor.setWarningMinValue(mChartPagerBean.majorWarningMin);//设置告警最小值
		rendererMajor.setWarningMaxValue(mChartPagerBean.majorWarningMax);//设置告警最大值
		//将曲线渲染对象添加到图表渲染器中
		mRenderer.addSeriesRenderer(rendererMajor);
		
		//如果图表中存在两条曲线，则再分别创建一个数据子集和一个曲线渲染对象
		if(mChartPagerBean.isHasSlave)
		{
			//创建一个数据子集
			XYSeries seriesSlave = new XYSeries(mChartPagerBean.slaveName);
			i=1;
			//将数据添加到数据子集中，并动态修改最大值和最小值
			for(int value : mChartPagerBean.slaveValueList)
			{
				value = mChartPagerBean.slaveValueList.get(i-1);
				seriesSlave.add(i, value);
				if(value<yAxisMin){
					yAxisMin = value;
				}
				if(value>yAxisMax){
					yAxisMax = value;
				}
				i++;
			}
			//将数据子集添加到图表数据集合中
			mDataset.addSeries(seriesSlave);
			//创建一个曲线渲染对象
			ColoursXYSeriesRenderer rendererSlave = new ColoursXYSeriesRenderer();
			rendererSlave.setPointStyle(PointStyle.CIRCLE);//设置为曲线图
			rendererSlave.setFillPoints(true);//数据点被填充
			rendererSlave.setDisplayChartValues(true);//在图表中显示点的值
			rendererSlave.setDisplayChartValuesDistance(1);//在X轴上，设置两点之间的距离
			rendererSlave.setColor(Color.YELLOW);//设置点的颜色
			rendererSlave.setChartValuesTextSize(25);//设置点值文本的尺寸大小
			rendererSlave.setChartValuesSpacing(15f);//实时数据文本到中心点的间距
			rendererSlave.setUseColor(true);//设置当前为双色曲线图
			rendererSlave.setWarningMinValue(mChartPagerBean.slaveWarningMin);//设置告警最小值
			rendererSlave.setWarningMaxValue(mChartPagerBean.slaveWarningMax);//设置告警最大值
			//将曲线渲染对象添加到图表渲染器中
			mRenderer.addSeriesRenderer(rendererSlave);
		}
		
		//设置图表XY轴的最大值和最小值
		mRenderer.setYAxisMin(yAxisMin);
	    mRenderer.setYAxisMax(yAxisMax);
	    mRenderer.setXAxisMin(1);
	    mRenderer.setXAxisMax(AppConfig.CHART_MAX_POINT+1);
		
		LinearLayout layout = (LinearLayout)getView().findViewById(R.id.chart);
	    layout.removeAllViews();
	    //创建图表view
		mChartView = ChartFactory.getLineChartView(getActivity(), mDataset, mRenderer);
		mRenderer.setApplyBackgroundColor(true);//开启背景颜色
		mRenderer.setBackgroundColor(Color.TRANSPARENT);//设置背景透明
		mRenderer.setMarginsColor(Color.TRANSPARENT);//设置边缘透明
		mRenderer.setSelectableBuffer(10);
		//将图表view添加图表容器中
		layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
		//图表重会
		mChartView.repaint();
	}
	//从数据库去读取传感器数据
	private void loadSensorDataFromDB()
	{
		Date now = new Date();
		//设置查询条件
		mSensorValueDB.loadSensorByTime(now.getTime()-mTimeGap, new BaseDB.OnDatabaseHandlerListener() {
			@Override
			//处理查询结果集
			public boolean onDatabaseHandler(ArrayList<Object> dataList,boolean isSuccess) 
			{
				Log.d(TAG,"load sensor data list:"+dataList.size()+" row");
				//清除老数据
				mChartPagerBean.majorValueList.clear();
				mChartPagerBean.slaveValueList.clear();
				//根据传感器类型设置相关曲线图表Y轴的最大值和值小值
				switch(mCurrentType)
				{
				case R.string.pm25_title:
					mChartPagerBean.majorName = getString(R.string.pm25_title);
					mChartPagerBean.majorMin = 0;//pm2.5的最小值
					mChartPagerBean.majorMax = 500;//pm2.5的最大值
					mChartPagerBean.majorWarningMin = -1000;//pm2.5的告警最小值
					mChartPagerBean.majorWarningMax = mSensorConfig.maxPM25;//pm2.5的告警最大值
					break;
				case R.string.CO2_title:
					mChartPagerBean.majorName = getString(R.string.CO2_title);
					mChartPagerBean.majorMin = 0;//co2的最小值
					mChartPagerBean.majorMax = 1000;//co2的最大值
					mChartPagerBean.majorWarningMin = mSensorConfig.minCo2;//co2的告警最小值
					mChartPagerBean.majorWarningMax = mSensorConfig.maxCo2;//co2的告警最大值
					break;
				case R.string.light_title:
					mChartPagerBean.majorName = getString(R.string.light_title);
					mChartPagerBean.majorMin = 0;//光照强度最小值
					mChartPagerBean.majorMax = 15000;//光照强度最大值
					mChartPagerBean.majorWarningMin = mSensorConfig.minLight;//光照强度的告警最小值
					mChartPagerBean.majorWarningMax = mSensorConfig.maxLight;//光照强度的告警最大值
					break;
				case R.string.air_tmper_title:
					mChartPagerBean.majorName = getString(R.string.air_tmper_title);
					mChartPagerBean.majorMin = 0;//空气温度最小值
					mChartPagerBean.majorMax = 100;//空气温度最大值
					mChartPagerBean.majorWarningMin = mSensorConfig.minAirTemperature;//空气温度的告警最小值
					mChartPagerBean.majorWarningMax = mSensorConfig.maxAirTemperature;//空气温度的告警最大值
					break;
				case R.string.air_humid_title:
					mChartPagerBean.majorName = getString(R.string.air_humid_title);
					mChartPagerBean.majorMin = 0;//空气湿度最小值
					mChartPagerBean.majorMax = 100;//空气湿度最大值
					mChartPagerBean.majorWarningMin = mSensorConfig.minAirHumidity;//空气湿度的告警最小值
					mChartPagerBean.majorWarningMax = mSensorConfig.maxAirHumidity;//空气湿度的告警最大值
					break;
				case R.string.soil_tmper_title:
					mChartPagerBean.majorName = getString(R.string.soil_tmper_title);
					mChartPagerBean.majorMin = 0;//土壤温度最小值
					mChartPagerBean.majorMax = 100;//土壤温度最大值
					mChartPagerBean.majorWarningMin = mSensorConfig.minSoilTemperature;//土壤温度的告警最小值
					mChartPagerBean.majorWarningMax = mSensorConfig.maxSoilTemperature;//土壤温度的告警最大值
					break;
				case R.string.soil_humid_title:
					mChartPagerBean.majorName = getString(R.string.soil_humid_title);
					mChartPagerBean.majorMin = 0;//土壤湿度最小值
					mChartPagerBean.majorMax = 100;//土壤湿度最大值
					mChartPagerBean.majorWarningMin = mSensorConfig.minSoilHumidity;//土壤湿度的告警最小值
					mChartPagerBean.majorWarningMax = mSensorConfig.maxSoilHumidity;//土壤湿度的告警最大值
					break;
				}
				mChartPagerBean.isHasSlave = false;
				if(dataList != null)
				{
					//根据传感器类型从结果集中提取相关的值
					for(int i=0; i<dataList.size(); i++)
					{
						SensorValue sensor = (SensorValue)dataList.get(i);
						switch(mCurrentType)
						{
						case R.string.pm25_title:
							mChartPagerBean.majorValueList.add(sensor.getPm25());
							break;
						case R.string.CO2_title:
							mChartPagerBean.majorValueList.add(sensor.getCo2());
							break;
						case R.string.light_title:
							mChartPagerBean.majorValueList.add(sensor.getLight());
							break;
						case R.string.air_tmper_title:
							mChartPagerBean.majorValueList.add(sensor.getAirTemper());
							break;
						case R.string.air_humid_title:
							mChartPagerBean.majorValueList.add(sensor.getAirHumid());
							break;
						case R.string.soil_tmper_title:
							mChartPagerBean.majorValueList.add(sensor.getSoilTemper());
							break;
						case R.string.soil_humid_title:
							mChartPagerBean.majorValueList.add(sensor.getSoilHumid());
							break;
						}
					}
				}
				dismissLoadDialog();
				//刷新曲线图表
				updataChartView();
				return false;
			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		System.gc();
	}
	
}
